package com.sinothk.cloud.mq.rabbit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sinothk.cloud.mq.websocket.bean.IMBean;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
public class RabbitMqProducer {

    private final RabbitTemplate rabbitTemplate;

    public RabbitMqProducer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    public void send(String queueName) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("email", "38151818@qq.com");
        jsonObject.put("timestamp", System.currentTimeMillis());
        String jsonString = jsonObject.toJSONString();

        // 生产者发送消息的时候需要设置消息id
        String uuid = UUID.randomUUID() + "";

        // 生产者发送消息的时候需要设置消息id
        Message message = MessageBuilder.withBody(jsonString.getBytes())
                .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                .setContentType(MessageProperties.CONTENT_TYPE_JSON).setContentEncoding("utf-8")
                .setMessageId(uuid)
                .build();
        //将messageId存入redis（在监听器判空，防止重复消费）
//        stringRedisTemplate.opsForValue().set("uuid ", uuid );

        rabbitTemplate.convertAndSend(queueName, message);
    }

    /**
     * 发送即时消息(json中定义IM的相关信息)
     *
     * @param iMBean
     */
    public void sendIm(IMBean iMBean) {
        // 生产者发送消息的时候需要设置消息id
        String uuid = UUID.randomUUID() + "";

        // 生产者发送消息的时候需要设置消息id
        Message message = MessageBuilder.withBody(JSON.toJSONString(iMBean).getBytes())
                .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                .setContentType(MessageProperties.CONTENT_TYPE_JSON).setContentEncoding("utf-8")
                .setMessageId(uuid)
                .build();
        //将messageId存入redis（在监听器判空，防止重复消费）
//        stringRedisTemplate.opsForValue().set("uuid ", uuid );

        rabbitTemplate.convertAndSend(RabbitMqQueue.IM, message);
    }
}

